#include "app_mqtt.h"
#include <MQTTClient.h>
#include "log.h"
#include <stdio.h>
#include"string.h"
static MQTTClient client;
//连接时候的一些设置
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
//发布消息的设置
static MQTTClient_message pubmsg = MQTTClient_message_initializer;

int (*app_mqtt_recv_callback)(char *);
/// @brief 连接失败的原因
/// @param context
/// @param cause
static void app_mqtt_connectionLost(void *context, char *cause)
{
    log_error(" mqtt  connectionLost :cause :%s", cause);
}


// 消息到达·回调函数
static int app_mqtt_messageArrived(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    // 1 把消息内容提取出来 , 用内部的回调函数调用（实质调用的内容 由外部注册）
    if (app_mqtt_recv_callback == NULL)
    {
        log_error(" app_mqtt_recv_callback is NULL");
        return 0;
    }
    log_info(" mqtt服务端发送来的数据  :%s", message->payload);
    int ret = app_mqtt_recv_callback(message->payload);
    log_info(" app_mqtt_recv_callback ret :%d", ret);
    if (ret == 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}
/**
 *  @brief mqtt消息发送成功后回调
 *  ps: 只有QoS1和QoS2才有效
 */

static void app_mqtt_deliveryComplete(void* context, MQTTClient_deliveryToken dt){
    log_info("消息发送完成...");
}



int app_mqtt_init(void)
{
    
    // 1.创建mqtt客户端                                                    客户端的持久化不开启
    int ret = MQTTClient_create(&client, MQTT_BROKER_URI, MQTT_CLIENT_ID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    if (ret == -1)
    {
        log_error(" MQTTClient_create error");
    }
    // 2. 设置mqtt客户端的回调函数
    MQTTClient_setCallbacks(client, NULL, app_mqtt_connectionLost, app_mqtt_messageArrived, app_mqtt_deliveryComplete);
    // 3. 连接mqtt服务器
   ret= MQTTClient_connect(client, &conn_opts);
   
   if(ret==-1){
        log_error(" MQTTClient_connect error");
        return -1;
   }
   log_info(" MQTTClient_connect success");   
   //  4. 订阅主题
   ret=MQTTClient_subscribe(client, MQTT_SUBSCRIBE_TOPIC, MQTT_QOS);
   if(ret==-1){
    log_error(" MQTTClient_subscribe error");
    return -1;
   }
   log_info(" MQTTClient_subscribe success");
   return 0;
}

/**
 * @brief 发布mqtt消息
 */
int app_mqtt_publish(char *payload){
    //给消息句柄赋值
    pubmsg.payload = payload;
    pubmsg.payloadlen = strlen(payload);
    log_info(" MQTTClient_publishMessage payload :%s",payload);
    int ret=MQTTClient_publishMessage(client, MQTT_PUBLISH_TOPIC, &pubmsg, NULL);
    if(ret==-1){
        log_error(" MQTTClient_publishMessage error");
        return -1;
    }
    log_info(" MQTTClient_publishMessage success");
    return 0;
}

/**
 * @brief 注册接收数据的回调函数
 */
int app_mqtt_register_recv_callback(int (*callback)(char *)){
    app_mqtt_recv_callback=callback;
    return 0;
}

/**
 * @brief 销毁mqtt
 */
void app_mqtt_destroy(){
    //断开连接
    MQTTClient_disconnect(client, 1000);
    MQTTClient_destroy(&client);
}
